﻿using AutoMapper;
using Modules;
using Modules.System.Flow;
using PmSoft;
using static Modules.System.Flow.FlowConstants;

namespace ManagementApi.Models.System.AuditLog
{
    public class AuditLogDto
    {
        /// <summary>
        /// 主键 
        ///</summary>
        public int Id { get; set; }
        /// <summary>
        /// 流程id 
        ///</summary>
        public int FlowId { get; set; }
        /// <summary>
        /// 步骤编码
        ///</summary>
        public FlowEngine FlowEngineCode { get; set; }
        /// <summary>
        /// 步骤名称
        ///</summary>
        public string FlowEngineName { get; set; }
        /// <summary>
        /// 顺序 
        ///</summary>
        public int? Sort { get; set; }
        /// <summary>
        /// 主表(业务表)id  
        ///</summary>
        public int ObjectId { get; set; }
        /// <summary>
        /// 审核状态  0,待审核  1.已审核 
        ///</summary>
        public Modules.Audit.SysAuditLogConstants.AuditStatus AuditStatus { get; set; }

        /// <summary>
        /// 审核状态名称
        ///</summary>
        public string AuditStatusName { get; set; }
        /// <summary>
        /// 审核意见 (1:成功  -1:失败) 
        ///</summary>
        public Modules.Audit.SysAuditLogConstants.AuditIdea? AuditIdea { get; set; }
        /// <summary>
        /// 审核意见名称
        ///</summary>
        public string AuditIdeaName { get; set; }
        /// <summary>
        /// 意见描述 
        ///</summary>
        public string AuditIdeaContent { get; set; }
        /// <summary>
        /// 创建时间 
        ///</summary>
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// 审核时间 
        ///</summary>
        public DateTime? AuditTime { get; set; }
        /// <summary>
        /// 创建人 
        ///</summary>
        public int CreateUserId { get; set; }
        /// <summary>
        /// 审核人 
        ///</summary>
        public int? AuditUserId { get; set; }
    }

    public static partial class AuditLogExceptions
    {
        public static IEnumerable<AuditLogDto> AsDto(this IEnumerable<SysAuditLog> sysAuditLogs)
        {
            List<AuditLogDto> auditLogDtos = new List<AuditLogDto>();
            var sysFlowEngineService = ServiceAccessor.GetService<SysFlowEngineService>();
            if (sysAuditLogs.Count() == 0) return null;
            var flowEngines = sysFlowEngineService.GetSysFlowEngineByFlowId(sysAuditLogs.First().FlowId);
            var mapper = ServiceAccessor.GetService<IMapper>();
            mapper.Map(sysAuditLogs, auditLogDtos);
            foreach (var item in auditLogDtos)
            {
                item.AuditStatusName = item.AuditStatus.GetDescription();
                item.AuditIdeaName = item.AuditIdea.GetDescription();
                item.FlowEngineName = flowEngines.Where(a => a.Code == item.FlowEngineCode).FirstOrDefault().Name;
            }
            return auditLogDtos;
        }
    }
}
